import { createRouter, createWebHashHistory } from 'vue-router'

import routesHome from './modules/home'
import routesNoPermission from './modules/no_permission'
import routesErrorPage from './modules/error_page'
import routesLast from './modules/last_route'
import routesStudy from './modules/study'

/*
var a = { name: '张三', age: 25 }
var b = { job: 'web前端', ...a }
相当于 var c = { job: 'web前端', name: '张三', age: 25 }
*/

// 定义首页
export const RoutesHome = [...routesHome]

// 定义一些不需要权限的基本页面，所有角色都可以进入
export const RoutesStatic = [...routesNoPermission, ...routesStudy, ...routesErrorPage]

// 定义放在最后的路由
export const RoutesLast = [...routesLast]

const initRouter = () => {
  return createRouter({
    // history 模式需要service支持
    // history: createWebHistory(process.env.BASE_URL),
    history: createWebHashHistory(process.env.BASE_URL),
    scrollBehavior: () => {
      return { y: 0 }
    },
    // 默认加载不需要验证的路由表
    routes: RoutesStatic,
  })
}

const router = initRouter()

export function resetRouter() {
  router.matcher = initRouter().matcher
}

export function addDynamicRoute(aryAccessedRoute) {
  resetRouter()
  // router.addRoutes(params)
  aryAccessedRoute.forEach((item) => {
    // router.options.routes = res
    // router.matcher = new VueRouter().matcher
    // router.addRoute(router.options.routes)
    router.addRoute(item)
  })
}

export default router
